import React, { Component } from 'react'
import store from '../../../redux'
import Api from '../../../config/api'
import Com from '../../../common/common'
import axios from 'axios'

import Table from 'antd/lib/table'
import Button from 'antd/lib/button'

import Navbar from '../../../Component/navbar'
import Spin from 'antd/lib/spin'
import Icon from 'antd/lib/icon'
import Input from 'antd/lib/input'
import Select from 'antd/lib/select'
import DatePicker from 'antd/lib/date-picker'
import Form from 'antd/lib/form'
import message from 'antd/lib/message'
import Modal from 'antd/lib/modal'

import moment from 'moment';
import 'moment/locale/zh-cn';
moment.locale('zh-cn');

const antIcon = <Icon type="loading" style={{ fontSize: 24, marginTop: 200 }} spin />;
const Option = Select.Option;
const FormItem = Form.Item;

let oper = null;

class OperBar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            startDate: '',
            endDate: '',
            startMonent: null,
            endMoment: null,
        }
    }
    componentDidMount() {
        axios.post(Api['updateUserProductParams']).then((res) => {
            if (res) {
                let data = JSON.parse(JSON.stringify(res.data))
                this.search();
                this.props.setPro(data)
            }
        }).catch((error) => {
            console.log(error)
        })
    }
    getTime(type, moment, time) {
        if (type === 'start') {
            this.setState({
                startDate: time,
                startMoment: moment
            })
        }
        else {
            this.setState({
                endDate: time,
                endMoment: moment
            })
        }
    }
    disabledstartTime(current) {
        if (this.state.endMoment) {
            return current > this.state.endMoment
        }
        else {
            return false
        }
    }
    disabledendTime(current) {
        if (this.state.startMoment) {
            return current < this.state.startMoment
        }
        else {
            return false
        }
    }
    search() {
        let obj = {
            account: this.accountInput.input.value,
            name: this.nameInput.input.value,
            startTime: this.state.startDate,
            endTime: this.state.endDate
        }
        this.props.search(obj)
    }
    render() {
        return (
            <Navbar ref={(item) => { oper = item }}>
                <Form layout="inline">
                    <FormItem label="账号"><Input style={{ width: '150px' }} ref={(input) => { this.accountInput = input }} /></FormItem>
                    <FormItem label="产品"><Input style={{ width: '150px' }} ref={(input) => { this.nameInput = input }} /></FormItem>
                    <FormItem label="开始时间">
                        <DatePicker format="YYYY-MM-DD" disabledDate={this.disabledstartTime.bind(this)} onChange={this.getTime.bind(this, 'start')} />
                    </FormItem>
                    <FormItem label="结束时间">
                        <DatePicker format="YYYY-MM-DD" disabledDate={this.disabledendTime.bind(this)} onChange={this.getTime.bind(this, 'end')} />
                    </FormItem>
                    <FormItem>
                        <Button type="primary" icon="search" onClick={this.search.bind(this)}>查询</Button>
                    </FormItem>
                </Form>
            </Navbar>
        )
    }
}

const ValidateOperbar = Form.create()(OperBar);

class Table1 extends Component {
    constructor(props) {
        super(props)
        this.state = {
            dataNum: 0,
            tableHeight: 300,
            tableData: this.props.tableData,
            showEditModal: false,
            nowRowId: 0,
            productData: [],
            lt: '',
            yd: '',
            dx: ''
        }
    }
    componentDidMount() {
        setTimeout(() => {
            let operbarHeight = oper.box.offsetHeight + 10 + 10;
            this.setState({
                tableHeight: store.getState().mainTableSize - operbarHeight - 45 - 33 - 71 - 15 - 30
            })
            this.unscribe = store.subscribe(this.fullTable.bind(this))
        }, 100)
        this.setState({
            productData: this.props.productData
        })
    }
    componentWillReceiveProps(nextprops) {
        this.setState({
            tableData: nextprops.tableData,
            dataNum: nextprops.dataNum,
            productData: nextprops.productData,
            currntPage: nextprops.currentPage
        })
    }
    componentWillUnmount() {
        this.unscribe()
    }
    fullTable() {
        let operbarHeight = oper.box.offsetHeight + 10 + 10;
        this.setState({
            tableHeight: store.getState().mainTableSize - operbarHeight - 45 - 33 - 71 - 15 - 30
        })
    }
    editModalShow(record) {
        this.state.productData.forEach((item) => {
            if (item.name === record.name) {
                this.setState({
                    yd: item.ydGatewayName,
                    lt: item.ltGatewayName,
                    dx: item.dxGatewayName
                }, () => {
                    this.props.form.setFieldsInitialValue({
                        account: record.account,
                        name: item.id,
                        ydGateways: this.state.yd,
                        ltGateways: this.state.lt,
                        dxGateways: this.state.dx
                    })
                    this.setState({
                        showEditModal: true,
                        nowRowId: record.id
                    })
                })
            }
        })
    }
    changePro(index) {
        this.state.productData.forEach((item) => {
            if (item.id === index) {
                this.setState({
                    yd: item.ydGatewayName,
                    lt: item.ltGatewayName,
                    dx: item.dxGatewayName
                }, () => {
                    this.props.form.setFieldsValue({
                        ydGateways: this.state.yd,
                        ltGateways: this.state.lt,
                        dxGateways: this.state.dx
                    })
                })
            }
        })
    }
    editCancel() {
        this.setState({
            showEditModal: false
        })
        this.props.form.resetFields()
    }
    editSure(e) {
        e.preventDefault();
        this.props.form.validateFields(['name', 'account'], (err, values) => {
            if (!err) {
                let data = JSON.parse(JSON.stringify(values))
                axios.post(Api['updateUserProduct'] + "?id=" + data.name + "&account=" + data.account).then(res => {
                    if (res) {
                        this.props.search();
                        this.props.form.resetFields()
                        message.success('提交成功')
                        this.setState({
                            showEditModal: false
                        })
                    }
                }).catch(function (error) {
                    console.log(error)
                })
            }
        });
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 18 },
            },
        };
        const columns = [
            { title: '客户账号', dataIndex: 'account', key: '1', width: 220 },
            { title: '产品', dataIndex: 'name', key: '2', width: 200 },
            { title: '移动通道', dataIndex: 'ydGatewayName', key: '3', width: 220 },
            { title: '联通通道', dataIndex: 'ltGatewayName', key: '4', width: 220 },
            { title: '电信通道', dataIndex: 'dxGatewayName', key: '5', width: 220 },
            { title: '创建时间', dataIndex: 'createTime', key: '6', width: 200 },
            {
                title: '操作',
                key: '7',
                width: 150,
                render: (record) => {
                    return (
                        <div>
                            <a onClick={this.editModalShow.bind(this, record)}>配置产品</a>
                        </div>
                    )
                }
            },
        ];
        return (
            <div className="common-table">
                <Table title={(data) => { return '客户产品列表' }} columns={columns} dataSource={this.state.tableData} pagination={{
                    onChange: this.props.changePage,
                    onShowSizeChange: this.props.changePageSize,
                    defaultPageSize: 20,
                    pageSizeOptions: ['20', '50', '100'],
                    showSizeChanger: true,
                    showQuickJumper: true,
                    current: this.state.currntPage,
                    total: this.state.dataNum,
                    showTotal: total => `共 ${total} 条数据`
                }} scroll={{ x: 1450, y: this.state.tableHeight }}></Table>
                <Modal visible={this.state.showEditModal} onCancel={this.editCancel.bind(this)} title="配置" footer={[
                    <Button key="sure" type="primary" onClick={this.editSure.bind(this)}>确定</Button>,
                    <Button key="cancel" type="danger" onClick={this.editCancel.bind(this)}>取消</Button>
                ]} >
                    <Form>
                        <FormItem label="账号" {...formItemLayout}>
                            {getFieldDecorator('account')(<Input disabled />)}
                        </FormItem>
                        <FormItem label="产品" {...formItemLayout}>
                            {getFieldDecorator('name', { validateFirst: true, rules: [{ required: true, message: '请输入产品名称', }, Com.validateSpace] })(
                                <Select onChange={this.changePro.bind(this)}>
                                    {this.state.productData.map((item, index) => {
                                        return <Option value={item.id} key={index}>{item.name}</Option>
                                    })}
                                </Select>
                            )}
                        </FormItem>
                        <FormItem label="移动通道" {...formItemLayout}>
                            {getFieldDecorator('ydGateways')(<Input disabled />)}
                        </FormItem>
                        <FormItem label="联通通道" {...formItemLayout}>
                            {getFieldDecorator('ltGateways')(<Input disabled />)}
                        </FormItem>
                        <FormItem label="电信通道" {...formItemLayout}>
                            {getFieldDecorator('dxGateways')(<Input disabled />)}
                        </FormItem>
                    </Form>
                </Modal>
            </div >
        )
    }
}

const ValidateTable = Form.create()(Table1);

class Box extends Component {
    constructor(props) {
        super(props)
        this.state = {
            totalNum: 0,
            tableData: [],
            searchParams: {},
            productData: [],
            paginationData: {
                current: 1,
                pageNum: 1,
                pageSize: 20
            },
            currentPage: 1,
            loading: true,
        }
    }
    setParams(obj) {
        let data = JSON.parse(JSON.stringify(obj));
        this.setState({
            searchParams: data,
        }, () => {
            this.search('btn');
        })
    }
    search(type) {
        let data = JSON.parse(JSON.stringify(this.state.searchParams));
        if (type === 'btn') {
            data.pageNum = 1;
            this.setState({
                currentPage: 1
            })
        } else {
            data.pageNum = this.state.paginationData.pageNum;
        }
        data.pageSize = this.state.paginationData.pageSize;
        this.setState({
            loading: true,
        })
        axios.post(Api['userProductByParams'], data).then((res) => {
            if (res) {
                let data = JSON.parse(JSON.stringify(res.data));
                data.list.forEach((item, index) => {
                    item.key = index;
                })
                this.setState({
                    loading: false,
                    tableData: data.list,
                    totalNum: data.total
                })
            }
        }).catch((error) => {
            console.log(error)
        })
        axios.post(Api['updateUserProductParams']).then((res) => {
            if (res) {
                let data = JSON.parse(JSON.stringify(res.data))
                this.setPro(data)
            }
        }).catch((error) => {
            console.log(error)
        })
    }
    setPro(data) {
        this.setState({
            productData: data
        })
    }
    changePageSize(current, size) {
        let pagination = JSON.parse(JSON.stringify(this.state.paginationData))
        pagination.pageNum = current;
        pagination.pageSize = size;
        this.setState({
            paginationData: pagination,
            currentPage: current
        }, () => { this.search('pag') })
    }
    changePage(pageNum, pageSize) {
        let pagination = JSON.parse(JSON.stringify(this.state.paginationData))
        pagination.pageNum = pageNum;
        pagination.pageSize = pageSize;
        this.setState({
            paginationData: pagination,
            currentPage: pageNum
        }, () => { this.search('pag') })
    }
    render() {
        return (
            <div>
                <ValidateOperbar search={this.setParams.bind(this)} setPro={this.setPro.bind(this)} />
                <Spin spinning={this.state.loading} indicator={antIcon}>
                    <ValidateTable
                        search={this.search.bind(this)}
                        tableData={this.state.tableData}
                        dataNum={this.state.totalNum}
                        currentPage={this.state.currentPage}
                        productData={this.state.productData}
                        changePageSize={this.changePageSize.bind(this)}
                        changePage={this.changePage.bind(this)}
                    />
                </Spin>
            </div>
        )
    }
}

export default Box